package network;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import network.NetworkPackage;
import network.UdpNetwork;
import network.UdpUtil;
import model.Smurf;
import model.World;
import com.jme3.math.Transform;

public class MonkeyUdpClient{

	private DatagramSocket socket;
	private Thread thread;
	private int updateInterval;
	
	public MonkeyUdpClient(final int id, final String ip){
		try {
			
			socket = UdpNetwork.openConnection();
			
			thread = new Thread(new Runnable() {
				@Override
				public void run() {
					try {
						
						int id = 0; // GET ID						
						Smurf s;						
						Transform t;
						
						while(true){
							
							long start = System.currentTimeMillis();							
							s = World.getInstance().getPlayer(id).getSmurf();
							t = s.getLocalTransform();							
							NetworkPackage npp = new NetworkPackage(id, t);							
							UdpNetwork.sendObject(socket, ip, 2600+id, npp);							
							DatagramPacket packet = UdpNetwork.readPackage(socket);
							Object object = UdpUtil.toObject(packet);							
							NetworkPackage[] mnps = (NetworkPackage[])object;
							
							for(NetworkPackage np : mnps){
								if(np != null){
									if(np.getId() != id){
										Smurf ms_tmp = World.getInstance().getPlayer(np.getId()).getSmurf();
										ms_tmp.setLocalTransform(np.getTransform());
									}
								}
							}
							
							long end = System.currentTimeMillis();
							System.out.println(end-start);
							
							try {
								if((end-start)<(updateInterval)){
									Thread.sleep((updateInterval)-(end-start));
								}else{
									System.out.println("Lagging after with "+((updateInterval)-(end-start))+" millis");
								}
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
							
						}
					} catch (IOException e1) {
						e1.printStackTrace();
					}				
				}
			});
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void start(int updateInterval){
		this.updateInterval = updateInterval;
		thread.start();		
	}
}
